package com.fanxuankai.commons.validation;

import com.fanxuankai.commons.exception.BizException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import java.util.Set;

/**
 * @author fanxuankai
 */
public class ValidationUtils {
    /**
     * 基于注解校验
     *
     * @param t      要校验的对象
     * @param groups 校验组，与注解的 groups 对应
     * @param <T>    对象类型
     */
    public static <T> void validate(T t, Class<?>... groups) {
        validate(t, false, groups);
    }

    /**
     * 校验
     *
     * @param t              要校验的对象
     * @param customValidate 是否自定义校验
     * @param groups         校验组，与注解的 groups 对应
     * @param <T>            对象类型
     */
    public static <T> void validate(T t, boolean customValidate, Class<?>... groups) {
        Set<ConstraintViolation<T>> result = Validation.buildDefaultValidatorFactory().getValidator()
                .validate(t, groups);
        for (ConstraintViolation<T> constraintViolation : result) {
            throw new BizException(400, constraintViolation.getMessage());
        }
        if (customValidate && t instanceof CustomValidator) {
            CustomValidator customValidator = (CustomValidator) t;
            if (groups == null) {
                customValidator.validate(null);
            } else {
                for (Class<?> group : groups) {
                    customValidator.validate(group);
                }
            }
        }
    }
}
